package com.refusea.train.utils

import com.refusea.commons.utils.Sn
import com.refusea.remoting.alibaba.OssApi
import com.refusea.train.domain.ex.BizEx
import java.util.Base64

/**
 * 将 html 里 base64 编码的图片上传到 oss，并转换为 oss 上的图片链接
 *
 * @author Zhang Yan 2024/4/2
 **/
object RichTexts {

    private val imgRegex = "<img\\s[^>]*>".toRegex()
    private val base64Regex = "data:image/(\\w+);base64,([A-Za-z0-9+/=]+)".toRegex()

    fun transform(html: String): String {
        var resultHtml = html
        imgRegex.findAll(html).forEach { match ->
            val imgTag = match.value
            val base64Match = base64Regex.find(imgTag)
            if (base64Match != null) {
                val (format, base64Content) = base64Match.destructured
                val content = Base64.getDecoder().decode(base64Content)
                val url = transformImg(format, content)
                val newImgTag = "<img src='$url'>"
                resultHtml = resultHtml.replace(imgTag, newImgTag)
            }
        }
        return resultHtml
    }

    private fun transformImg(format: String, content: ByteArray): String {
        val sn = Sn.next16()
        if (OssApi.put("static-refusea", "train/${sn}.${format}", content, format = format)) {
            return "https://static.refusea.com/train/${sn}.${format}"
        }
        throw BizEx.of("上传图片失败，格式为：$format")
    }
}
